from django import newforms as forms
from plzkeepthat.common import messages 
import logging 

class TagField(forms.Field):
    """ A field for entering a comma-separated-list of tags """
    
    def __init__(self):
        forms.Field.__init__(self, widget = forms.TextInput(attrs = {
                           'class':'tagsText'
                           }))
        self.DELIMITERS = (".", " ", "#",  ":", "/", "\\")
        self.TAG_SPLITTER = ','
    
    def __delete_if_empty(self, value):
        if value and value != '': return value
        else: return None
    
    def clean(self, value):
        """ Check that the field contains one or more comma-separated tags and 
        normalizes the data to a list of the tags. """
        
        if not value: raise forms.ValidationError(messages.EMPTY_FIELD_ERROR)
        
        for delim in self.DELIMITERS: value = value.replace(delim, "")
        results = []
        for v in value.split(self.TAG_SPLITTER):
            if v is not None and v != '':results.append(v)          
        return results
    
class MultiEMailField(forms.Field):
    """ A field for entering a list of mail recipients """
    def __init__(self):
        forms.Field.__init__(self, required = True, widget = forms.TextInput(attrs = {
                           'class':'toText'
                           }))
    def clean(self, value):
        tag_splitter = ','

        if not value:
            raise forms.ValidationError(messages.EMPTY_FIELD_ERROR)
        if value.endswith(tag_splitter): value = value[:-1]
        l = []
        for v in value.split(tag_splitter):
            if len(v) != 0: l.append(v) 
        return l
